from django.views import View
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from common.views.utils import table_api
from django.core.paginator import Paginator
from django.db.models import Q
from ..models.models import Role

class RoleListView(View):
    @method_decorator(login_required)
    def get(self,request):
        filters = []
        page = request.GET.get('page')
        limit = request.GET.get('limit')
        name = request.GET.get('name')
        code = request.GET.get('code')
        if name:
            filters.append(Q(name__icontains=name))
        if code:
            filters.append(Q(code__icontains=code))
        roles = Paginator(Role.objects.filter(*filters).order_by('ca_time'),limit).get_page(page)
        result = [{
            'id': item.id,
            'name':item.name,
            'code':item.code,
            'enable':item.enable,
            'remark':item.remark,
            'details':item.details,
            'ca_time':item.ca_time.strftime('%Y-%m-%d %H:%M:%S'),
            'up_time':item.up_time.strftime('%Y-%m-%d %H:%M:%S'),
        } for item in roles]

        return table_api(result=result,total=roles.paginator.count)